import { useEffect, useState, useRef, useCallback } from "react";
import { useReadContract, useReadContracts } from "wagmi";
import { bscTestnet } from "wagmi/chains";
import { miningContract } from "../../provider/Contract";
import Big from "big.js";
import Receive, { ReceiveComponentType } from "./receive";
import type { PoolType } from "../../types";
import Pool from "./pool";

const Home: React.FC = () => {
    const receiveRef = useRef<ReceiveComponentType>(null);
    const [pools, setPools] = useState<PoolType[]>([]);

    // 获取 poolsLength
    const {
        data: poolLengthData,
        // isSuccess: poolLengthSuccess,
        refetch: refetchPoolLength,
    } = useReadContract({
        ...miningContract,
        functionName: "poolsLength",
    });

    // 生成 ids 数组，直接基于 poolLengthData
    const ids = poolLengthData
        ? [...new Array(Number(poolLengthData)).keys()]
        : [];

    // 获取 pools 数据
    const {
        data: contractsData,
        isSuccess: contractsSuccess,
        refetch: refetchContracts,
    } = useReadContracts({
        contracts: ids.map((id) => ({
            ...miningContract,
            functionName: "Pools",
            args: [id],
        })),
        query: {
            enabled: !!poolLengthData && ids.length > 0,
        },
        multicallAddress: bscTestnet.contracts.multicall3.address,
    });

    // 更新 pools 数据
    useEffect(() => {
        if (contractsSuccess && contractsData) {
            const newPools = contractsData.map((item) => {
                const res = item.result as string[];
                return {
                    miningId: res[0].toString(),
                    symbol: res[1].toString(),
                    tokenAddress: res[2].toString(),
                    total: new Big(res[3].toString())
                        .div(new Big("1e18"))
                        .toString(),
                    stakingNum: res[4].toString(),
                    rate: res[5].toString(),
                };
            });
            console.log("newPools", newPools);
            // 使用函数式更新，避免不必要的渲染
            setPools((prevPools) => {
                if (JSON.stringify(prevPools) !== JSON.stringify(newPools)) {
                    return newPools;
                }
                return prevPools;
            });
        }
    }, [contractsData, contractsSuccess]);

    // 统一 refetch 函数
    const refetch = useCallback(() => {
        refetchContracts();
        refetchPoolLength();
        if (receiveRef.current) {
            receiveRef.current.refetchAll();
        }
    }, [refetchContracts, refetchPoolLength]);

    return (
        <div>
            TEST
            <div>
                {poolLengthData ? poolLengthData.toString() : "Loading..."}
            </div>
            {pools.map((pool, index) => (
                <Pool key={index} pool={pool} refetch={refetch} />
            ))}
            <Receive ref={receiveRef} />
        </div>
    );
};

export default Home;
